<template>
  <qx-table :dbRowClick="rowDblClick" :option="tableOption" :remoteData="remoteData">
    <template v-slot:top>
      <qx-form v-model="searchForm" :option="tableOption" isSearch @submit="startSearch"></qx-form>
    </template>
    <template v-slot:menuLeft>
      <q-btn color="primary" icon="add" unelevated @click="handleCreate">
        {{ $t('Add') }}
      </q-btn>
    </template>
    <template v-slot:menuLeftR>
      <q-icon color="warning" name="mdi-map-marker-question cursor-pointer cursor-hover" size="1.5rem">
        <q-tooltip class="q-pa-md" v-bind="$tooltipAttr">{{ $t('Misc.DblClickCardTips') }}</q-tooltip>
      </q-icon>
    </template>
    <template v-slot:menu="{ row }">
      <q-btn class="col" color="primary" icon="mdi-square-edit-outline" outline unelevated @click="handleUpdate(row)">
        {{ $t('Edit') }}
      </q-btn>
      <q-btn class="col" color="primary" icon="delete" outline unelevated @click="handleDelete(row)">
        {{ $t('Del') }}
      </q-btn>
    </template>
  </qx-table>
  <q-modal v-model="modalVisible" :header="formInfo.id ? $t('Edit') : $t('Add')" :width="500" btnAlign="center"
           position="right" @beforeClose="beforeClose" @confirm="submitForm">
    <qx-form ref="FormRef" v-model="formInfo" :option="tableOption">
      <template v-slot:offsetXY="{ attrs  = {} }">
        <div class="row justify-between no-wrap">
          <q-number v-model="formInfo.offsetX" class="col" decimals="0" v-bind="attrs" v-bind:placeholder="'x'"
                    v-bind:rules="getRules('X')"></q-number>
          <div class="row items-end q-px-xs">,</div>
          <q-number v-model="formInfo.offsetY" class="col" decimals="0" v-bind="attrs" v-bind:placeholder="'y'"
                    v-bind:rules="getRules('Y')"></q-number>
          <div class="row items-center q-pl-xs">mm</div>
        </div>
      </template>
      <template v-slot:offsetAngleH="{ column = {} }">{{ `${column.label}(°)` }}</template>
    </qx-form>
  </q-modal>
  <q-modal v-model="infoVisible" :header="`${$t('Misc.SpecifyDetails')}`" :menuBtn="false" :persistent="false"
           width="620">
    <QInfo :columns="tableOption.column || []" :rowInfo="formInfo" cols="2" headerWidth="100"></QInfo>
  </q-modal>
</template>
<script setup>
import { i18n, toI18nName } from 'boot/i18n.js'
import { deleteAPI, postAPI, putAPI } from 'src/api/index.js'
import { getRemoteData, setRemoteData } from 'src/enum/ajaxRemoteData.js'
import { computed, onMounted, ref, watch } from 'vue'
import { createDialog, deepClone, isEmpty } from 'src/utils/utils.js'

const props = defineProps({
  modelValue: Boolean, isRefresh: { type: Boolean, default: false }, rowInfo: { type: Object, default: () => ({}) }
})
const emits = defineEmits(['update:isRefresh'])

const formInfo = ref({})
const FormRef = ref(null)
const AGVBrands = ref([])
const searchForm = ref({})
const infoVisible = ref(false)
const modalVisible = ref(false)
const remoteData = ref({ dicUrl: '/tpm/yfagv/api/newMapMonitorConverCfg/list' })
getRemoteData('agv_brand', '/yfagv/api/agvCfgBrand/list').then(data => (AGVBrands.value = data))
const tableOption = computed(() => {
  return {
    grid: true, span: 22, export: true, labelWidth: 100, searchSpan: 4, headerWidth: 70,
    searchLabelWidth: 60,
    column: [{
      label: `${i18n.t('AGVCore.AGVBrand')}`, field: 'agvBrandCode', type: 'select', options: AGVBrands.value,
      minWidth: 100, props: { label: `${toI18nName('agvBrandNameZhCn')}`, value: 'agvBrandCode' },
      topLeft: true, required: true
    }, {
      label: `${i18n.t('MapCore.AGVLocationMap')}`, field: 'mapCode', minWidth: 100, required: true, topRight: true
    }, {
      label: `${i18n.t('MapCore.CoordOffSet')}`, field: 'offsetXY', required: true, minWidth: 100, search: false,
      format: (_, row) => `${row.offsetX || 0},${row.offsetY || 0}mm`, formslot: true
    }, {
      label: `${i18n.t('MapCore.YawAngle')}`, field: 'offsetAngle', type: 'number', required: true, minWidth: 70,
      search: false, format: val => `${val || 0}°`
    }, {
      label: `${i18n.t('CreationTime')}`, field: 'createdTime', display: false, minWidth: 80, search: false,
      hide: true
    }]
  }
})

const getRules = coord => {
  return [val => !isEmpty(val) || `${i18n.t('PleaseInput')}${i18n.t('MapCore.SpecifyCoordOffSet', { coord })}`]
}
const handleCreate = () => {
  formInfo.value = {}
  modalVisible.value = true
}
const rowDblClick = row => {
  formInfo.value = row
  infoVisible.value = true
}
const handleUpdate = row => {
  formInfo.value = deepClone(row)
  modalVisible.value = true
}
const handleDelete = row => {
  createDialog({ msg: `${i18n.t('DelTips')}` }, () => {
    deleteAPI(`/tpm/yfagv/api/newMapMonitorConverCfg/${row.id}`, {}, () => startSearch('refresh'))
  }, () => {})
}
const formatSearchForm = () => {
  const params = { ...searchForm.value }, { newMapId } = props.rowInfo
  params.newMapId = newMapId
  return { ...params }
}
const startSearch = (action, done) => {
  remoteData.value.params = formatSearchForm()
  remoteData.value.clearSelected = true
  if (action === 'clear') remoteData.value.clearRows = true
  if (action === 'refresh') {
    emits('update:isRefresh', true)
    const { mapGroundCode } = props.rowInfo
    setRemoteData(`${mapGroundCode}_agv_brand`)
  }
  if (done) done()
}
const beforeClose = () => {
  if (FormRef.value) FormRef.value.onReset()
  modalVisible.value = false
}
const submitForm = mDone => {
  FormRef.value.validate((form, done) => {
    const { mapGroundCode: newMapGroundCode, newMapId } = props.rowInfo
    form.newMapId = newMapId
    form.newMapGroundCode = newMapGroundCode
    const API = form.id ? putAPI : postAPI
    API('/tpm/yfagv/api/newMapMonitorConverCfg', form, () => {
      startSearch('refresh')
      done()
      mDone && mDone()
    }, () => {
      done()
      mDone && mDone(false)
    })
  }, () => mDone && mDone(false))
}
watch(() => props.modelValue, val => val && startSearch('clear'))
onMounted(startSearch)
</script>